<template>
  <div class="app-container">
    <div class="title">
      <div v-if="this.$route.params && this.$route.params.id">修改讲师</div>
      <div v-else>添加讲师</div>
    </div>
    <el-form
      ref="teacherForm"
      :model="teacher"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="讲师名称" prop="name">
        <el-input v-model="teacher.name" />
      </el-form-item>
      <el-form-item label="讲师排序" prop="sort">
        <el-input-number
          v-model="teacher.sort"
          controls-position="right"
          :min="1"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="讲师头衔" prop="level">
        <el-select v-model="teacher.level" placeholder="请选择">
          <el-option label="高级讲师" :value="1" />
          <el-option label="首席讲师" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历" prop="career">
        <el-input v-model="teacher.career" />
      </el-form-item>
      <el-form-item label="讲师简介" prop="intro">
        <el-input v-model="teacher.intro" type="textarea" :rows="10" />
      </el-form-item>
      <!-- 讲师头像 -->
      <el-form-item label="讲师头像">
        <!-- 头像缩略图 -->
        <PanThumb :image="teacher.avatar"></PanThumb>
        <el-button
          type="primary"
          class="el-icon-upload"
          @click="imageCropperShow = true"
          >更换头像</el-button
        >
        <!-- 头像剪裁 -->
        <!-- key 的值头像剪裁插件的唯一标识
        url：上传图片的api地址
        field:请求api事需要发送字段名（后端api所约定的）
        colse：关闭头像插件时调用的方法
        crop-upload-success:头像上传成功时候调用的方法
         -->
        <ImageCropper
          v-show="imageCropperShow"
          @close="close"
          :width="300"
          :height="300"
          :key="imageCropperKey"
          :url="`${BASE_URL}/file/upload?host=avatar`"
          field="file"
          @crop-upload-success="cropSuccess"
        ></ImageCropper>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import teacherApi from "@/api/teacher";
import PanThumb from "@/components/PanThumb";
import ImageCropper from "@/components/ImageCropper";
export default {
  components: {
    PanThumb,
    ImageCropper,
  }, //注册组件
  data() {
    return {
      BASE_URL: process.env.BASE_API, //获取dev文件中的API地址
      imageCropperKey: 1, //头像剪裁组件的key
      imageCropperShow: false, //头像剪裁是否显示
      // 讲师数据
      teacher: {
        //teacher.avatar代替
        // name: "", //讲师姓名
        // intro: "", //简介
        // career: "", //资历
        // level: 1, //头衔
        // sort: 0, //排序
      },
      //验证规则
      rules: {
        name: [
          { required: true, message: "请输入讲师姓名", trigger: "blur" },
          { max: 5, message: "长度最大为5个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "排序必须是数字", trigger: "blur" },
          { required: true, message: "请输入序号", trigger: "blur" },
        ],
        level: [{ required: true, message: "请选择讲师头衔", trigger: "blur" }],
        career: [
          { required: true, message: "请输入讲师资历", trigger: "blur" },
        ],
        intro: [{ required: true, message: "请输入讲师简介", trigger: "blur" }],
      },
    };
  },
  //通过路由监视，触发页面初始化的方法
  watch: {
    $route(to, from) {
      this.init();
    },
  },
  created() {
    this.init();
  },
  methods: {
    //   提交表单
    onSubmit() {
      this.$refs["teacherForm"].validate((valid) => {
        if (valid) {
          // 判断执行的是更新(有id值)还是添加(没有id值)
          if (this.teacher.id) {
            // console.log("执行编辑")
            this.updateTeacher();
          } else {
            // console.log("执行添加")
            this.addTeacher();
          }
        }
      });
    },
    // 添加讲师
    addTeacher() {
      teacherApi.addTeacher(this.teacher).then((res) => {
        // 提示成功信息
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //   跳转至讲师列表页面   通过编程式导航
        this.$router.push({ path: "/teacher" });
      });
    },
    // 更新讲师
    updateTeacher() {
      // 调用更新API
      teacherApi.updateTeacher(this.teacher).then((res) => {
        // 更新成功后提示
        this.$message({
          type: "success",
          message: "更新成功!",
        });
        //   跳转至讲师列表页面   通过编程式导航
        this.$router.push({ path: "/teacher" });
      });
    },
    //  页面初始化 切换清空
    init() {
      // 判断执行的是更新(有id值)还是添加(没有id值)
      if (this.$route.params && this.$route.params.id) {
        // 执行更新操作
        // console.log("执行更新操作")
        // 根据id调用讲师API
        const id = this.$route.params.id;
        teacherApi
          .getTeacher(id)
          .then((res) => {
            // 将讲师信息添加到表单中
            this.teacher = res.data;
          })
          .catch((err) => {
            this.$message({
              type: "error",
              message: "获取数据失败!",
            });
          });
      } else {
        // 执行添加操作
        // console.log("执行添加操作")
        this.teacher = {
          avatar:
            "https://hopu-lesson.oss-cn-hangzhou.aliyuncs.com/avatar_default.png",
        };
      }
    },
    cropSuccess(data) {
      console.log(data);

      // 关闭头像剪裁插件
      this.imageCropperShow = false;
      //显示上传后的头像图片
      this.teacher.avatar = data.ossUrl;

      //修改头像剪裁插件的key,使其进行初始化
      this.imageCropperKey = this.imageCropperKey + 1;
    },
    // 关闭头像剪裁
    close() {
      this.imageCropperShow = false;
      //修改头像剪裁插件的key,使其进行初始化
      this.imageCropperKey = this.imageCropperKey + 1;
    },
  },
};
</script>

<style scoped>
.line {
  text-align: center;
}
.title {
  font-weight: 700;
  font-size: 19px;
  color: #000;
  margin-bottom: 10px;
  margin-left: 10px;
}
</style>

